package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.entity.Borrow;
import com.example.demo.entity.User;
import com.example.demo.mapper.BorrowMapper;
import com.example.demo.service.IBorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BorrowService extends ServiceImpl<BorrowMapper, Borrow>implements IBorrowService {
    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;
    @Override
    public Result saveBorrow(Borrow obj) {
        if (isOverBorrow(obj.getUserId())){
            return Result.error("超过最大借阅数量");
        }
        //根据图书id 查询图书信息
        if (obj.getBookId() == null) {
            return Result.error("图书id不能为空");
        }
        Book book = bookService.getById(obj.getBookId());
        if (book == null) {
            return Result.error("图书不存在");
        }
        if (book.getAvailable() <= 0) {
            return Result.error("图书库存不足");
        }
        book.setBorrowed(book.getBorrowed() + 1);
        book.setAvailable(book.getAvailable() - 1);
        //根据用户id查询用户信息
        User user = userService.getById(obj.getUserId());
        if (user == null) {
            return Result.error("用户不存在");
        }
        //生成订单信息
        obj.setUserName(user.getName());
        obj.setUserGrade(user.getGrade());
        obj.setUserMajor(user.getMajor());
        obj.setStatus("待还");
        obj.setBookName(book.getName());
        obj.setBookCategory(book.getCategory());
        obj.setBorrowDate(new Date());
        obj.setDueDate(new Date(obj.getBorrowDate().getTime() + 7 * 24 * 60 * 60 * 1000));//借阅时间+7天
        //更改图书表中的库存
        book.setBorrowed(book.getBorrowed() );
        book.setAvailable(book.getAvailable() );
        bookService.updateById(book);
        //保存借阅信息
        borrowMapper.insert(obj);
        return Result.success("借阅成功");
    }

    @Override
    public Result removeByIdBorrow(Integer id) {
        //删除订单
        //根据订单id查询订单
        Borrow borrow = borrowMapper.selectById(id);
        if (borrow == null) {
            return Result.error("订单不存在");
        }
        //根据图书id查询图书
        Book book = bookService.getById(borrow.getBookId());
        if (book == null) {
            return Result.error("图书不存在");
        }
        //更改图书表中的库存
        book.setBorrowed(book.getBorrowed() - 1);
        book.setAvailable(book.getAvailable() + 1);
        //删除订单信息
        return borrowMapper.deleteById(id)>0?Result.success("删除成功"):Result.error("删除失败");
    }

    @Override
    public Result saveRetur(Borrow obj) {
        //根据订单id查询订单
        Borrow borrow = borrowMapper.selectById(obj.getId());
        if (borrow == null) {
            return Result.error("订单不存在");
        }
        //根据图书id查询图书
        Book book = bookService.getById(borrow.getBookId());
        if (book == null) {
            return Result.error("图书不存在");
        }
        //更改图书表中的库存
        book.setBorrowed(book.getBorrowed() - 1);
        book.setAvailable(book.getAvailable() + 1);
        //更改订单信息
        borrow.setReturnDate(new Date());
        borrow.setStatus("已还");
        return borrowMapper.updateById(borrow)>0?Result.success("还书成功"):Result.error("还书失败");
    }

    @Override
    public List<Borrow> saveAll(List<Borrow> borrows) {
        //插入列表内的数据到数据库中
        return borrows.stream().map(borrow -> {
            //根据图书id 查询图书信息
            if (borrow.getBookId() == null) {
                return null;
            }
            Book book = bookService.getById(borrow.getBookId());
            if (book == null) {
                return null;
            }
            book.setBorrowed(book.getBorrowed() + 1);
            book.setAvailable(book.getAvailable() - 1);
            bookService.save(book);
            //根据用户id查询用户信息
            User user = userService.getById(borrow.getUserId());
            if (user == null) {
                return null;
            }
            //生成订单信息
            borrow.setUserName(user.getName());
            borrow.setUserMajor(user.getMajor());
            borrow.setUserGrade(user.getGrade());
            borrow.setStatus("待还");
            borrow.setBookName(book.getName());
            borrow.setBookCategory(book.getCategory());
            borrow.setBorrowDate(new Date());
            borrow.setDueDate(new Date(borrow.getBorrowDate().getTime() + 7 * 24 * 60 * 60 * 1000));//借阅时间+7天
            //更改图书表中的库存
            book.setBorrowed(book.getBorrowed() + 1);
            book.setAvailable(book.getAvailable() - 1);
            bookService.updateById(book);
            //保存借阅信息
            borrowMapper.insert(borrow);
            return borrow;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Borrow> listByUserId(Integer id) {
        //根据用户id查询订单
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        return borrowMapper.selectList(queryWrapper);
    }
    //查询用户借阅图书是否超过5个
    public boolean isOverBorrow(Integer id) {
        //根据用户id查询订单
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        queryWrapper.eq("status", "待还");
        List<Borrow> borrows = borrowMapper.selectList(queryWrapper);
        if (borrows.size() >= 5) {
            return true;
        }
        return false;
    }
}

